package com.luo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.luo.model.*;
import com.luo.service.GoodService;
import com.luo.util.ListTypes;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

/**
 * 功能：根据商品二级id分页查询商品
 * 作者：Luo。
 * 日期：2024/1/15 16:43
 */
@WebServlet("/category/goods/temporary")
public class GoodsListSomeByTwoClassId extends HttpServlet {

	GoodService goodService = new GoodService();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String pageFrom = req.getParameter("page");
		String pageSizeFrom = req.getParameter("pageSize");
		String categoryIdFrom = req.getParameter("categoryId");
		String sortFieldFrom = req.getParameter("sortField");
		GoodByTwoClassId goodByTwoClassId = new GoodByTwoClassId();
		goodByTwoClassId.setPage(Integer.parseInt(pageFrom));
		goodByTwoClassId.setPageSize(Integer.parseInt(pageSizeFrom));
		goodByTwoClassId.setSortField(sortFieldFrom);
		goodByTwoClassId.setCategoryId(categoryIdFrom);
		int pageSize = goodByTwoClassId.getPageSize();
		int page = goodByTwoClassId.getPage();
		int newPage = (page - 1) * pageSize;
		goodByTwoClassId.setPage(newPage);
		List<Goods> goods = goodService.queryGoodSomeByTwoClassId(goodByTwoClassId);

		for (Goods good : goods) {
			Double disCount = Double.valueOf(good.getDiscount()) / 10;
			Double price = Double.valueOf(good.getPrice());
			if (disCount > 0.0) {
				good.setOldPrice(String.format("%.2f", price * disCount));
			} else {
				good.setOldPrice(String.format("%.2f", price));
			}
		}

		ResultObj result = new ResultObj();
		result.setCode(1 + "");
		result.setMsg("查询成功");
		GoodByTwoClassIdRespone goodByTwoClassIdRespone = new GoodByTwoClassIdRespone();
		goodByTwoClassIdRespone.setItems(goods);
		result.setResult(goodByTwoClassIdRespone);
		String jsonString = JSON.toJSONString(result);
		resp.getWriter().write(jsonString);
		resp.getWriter().close();
	}
}
